<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" size="medium" :model="studentSearch" class="demo-form-inline"><el-form-item >
        <el-input v-model="studentSearch.sname" placeholder="学生姓名"></el-input>
        </el-form-item>
          <el-form-item >
            <el-input v-model="studentSearch.addr" placeholder="学生住址"></el-input>
          </el-form-item>
        <el-form-item >
          <el-select v-model="studentSearch.cid" placeholder="所在班级">
            <el-option label="所有班级" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search"  plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addStudent">添加</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="studentList"
          style="width: 100%">
        <el-table-column
            label="学号"
            align="center"
            prop="sid"
            width="180"/>
        <el-table-column
            label="姓名"
            prop="sname"
            align="center"/>
        <el-table-column
            label="性别"
            prop="sex"
            align="center"/>
        <el-table-column
            label="年龄"
            prop="age"
            align="center"/>
        <el-table-column
            label="住址"
            prop="addr"
            align="center"/>
        <el-table-column
            label="所在班级"
            prop="cname"
            align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
  </div>

  <!--添加-->
  <div>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      {{student}}
      <el-form :model="student" :rules="rules" ref="ruleForm">
        <el-form-item label="学生姓名" prop="sname" :label-width="formLabelWidth">
          <el-input v-model="student.sname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生性别" prop="sex" :label-width="formLabelWidth">
          <el-radio v-model="student.sex" label="男">男</el-radio>
          <el-radio v-model="student.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="学生年龄" prop="age" :label-width="formLabelWidth">
          <el-input v-model.number="student.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生地址" prop="addr" :label-width="formLabelWidth">
          <el-input v-model="student.addr" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="全部班级" prop="cid" :label-width="formLabelWidth">
          <el-select v-model="student.cid" placeholder="所在班级">
            <el-option label="全部班级" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveStudent">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import studentApi from "@/api/student"
import classesApi from "@/api/classes"
export default {
  data() {
    let CkAge = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('请输入值'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('请输入数字'))
      } else if (value < 1 || value > 200) {
        return callback(new Error('请输入1—200值'))
      } else {
        callback()
      }
    }
    return {
      studentList: [],
      page: 1,        // 当前面
      pageSize: 5,    // 每页显示条数
      total: 100,     // 总数
      studentSearch: {},
      classesList: [],   // 所有班级
      dialogFormVisible: false,  //显示 false不显示 true:
      student: {},
      title: '添加学生',
      formLabelWidth: '100px',
      multipleSelection:[],
      sids: [],
      rules: {
        sname: [
          {required: true, message: '请输入学生姓名', trigger: 'blur'},
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'},
        ],
        age: [
          { validator : checkAge, trigger: 'blur'}
        ],
        addr: [
          {required: true, message: '请输入学生住址', trigger: 'blur'},
        ],
        cid: [
          {required: true, message: '请选择学生班级', trigger: 'blur'},
        ]
      }
    }
  },
  created() {
    this.findStudents()
    this.findByPage()
    this.search()
    this.findAllClasses()
  },
  methods: {
    async findByPage() {
      const {data:res} = await studentApi.findByPage(this.page,this.pageSize)
      console.log(res)
      if (res.code === 200) {
        this.studentList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    async findStudents() {
      const {data:res} = await studentApi.findAllStudents()
      console.log(res)
      if (data.code === 200) {
        this.studentList = res.data.list
      }
    },
    async findAllClasses() {
      const {data:res} = await classesApi.findAllClasses()
      console.log(res)
      if (res.code === 200) {
        this.classesList = res.data.list
      }
    },
    async search(){
      const {data:res} = await studentApi.search(this.page,this.pageSize,this.studentSearch)
      console.log(res)
      if (res.code === 200) {
        this.studentList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    editStudent(){
      this.flag=2
      this.dialogFormVisible = true
    },
    addStudent(){
      this.flag=1
      this.title='添加学生'
      this.student = {}
      this.dialogFormVisible = true
    },
    async saveStudent(){
      this.$refs.ruleForm.validate(async valid=>{
        console.log(this.student)
        if(this.flag==1){
          const {data:res} = await studentApi.save(this.student)
          if (res.code === 200){
            this.$message({
              type: 'success',
              message: res.message
            })
            this.dialogFormVisible = false
            this.search()
          }else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        }else{
          const {data:res} = await studentApi.update(this.student)
          if (res.code === 200){
            this.$message({
              type: 'success',
              message: res.message
            })
            this.dialogFormVisible = false
            this.search()
          }else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        }
      })
    },
    handleEdit(index, row) {
      this.title= '编辑学生'
      console.log(index, row);
      this.flag = 2
      this.student = row
      this.dialogFormVisible = true
      console.log(this.student)
    },
    async handleDelete(index, row) {
      console.log(index, row);
      this.student = row
      console.log(this.student)
      const {data} = await studentApi.delete(this.student.sid)
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.search()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.search()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },
    async batchDelete(){
      this.multipleSelection.forEach(item => {
        this.ids.push(item.sid)
      })
      await studentApi.deleteBatch(this.ids).then(res => {
        if (res.data.code === 200){
          this.$message({
            type: 'success',
            message: res.data.message
          })
          this.search()
        }else {
          this.$message({
            type: 'error',
            message: res.data.message
          })
        }
      })
    }
  }
}
</script>

<style>
  #app{
    display: flex;
    justify-content: center;
  }
  .el-card{
    width: 90%;
  }
  .el-pagination{
    margin-top: 20px;
    text-align: right;
  }
</style>
